<template>
    <div class="category-detail-page">
        <el-card shadow="never">
            <el-form
                :model="form"
                label-position="right"
                label-suffix=":"
                label-width="100px"
                ref="form"
                :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入课程小节名称"
                    ></el-input>
                </el-form-item>
                <el-form-item label="关联学习主题" prop="course_ids">
                    <el-button type="primary" @click="getCourse">{{ "将本题关联到一个学习主题" }}</el-button>
                    <course-list
                        v-show="form.courses.length > 0"
                        :list="form.courses"
                        @delete="deleteCourse"></course-list>
                </el-form-item>
                <el-form-item label="讲师" prop="teacher_ids">
                    <el-button type="primary" @click="getTeachers">{{ "选取讲师" }}</el-button>
                    <teacher-list
                        v-show="form.teachers.length > 0"
                        :list="form.teachers"
                        @delete="deleteTeacher"></teacher-list>
                </el-form-item>
                <el-form-item label="类型">
                    <el-radio-group v-model="form.type">
                        <el-radio :label=1>文章</el-radio>
                        <el-radio :label=2>视频</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="视频" v-if="form.type === 2">
                    <file-upload
                    :type="1"
                    :multiple="false"
                    :accept="'.mp4,.rmvb,.avi'"
                    v-model="form.video">
                        <el-button type="primary">上传</el-button>
                    </file-upload>
                    或
                    <el-input
                        v-model="form.video"
                        placeholder="请输入视频链接地址"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <tinymce v-model="form.content"></tinymce>
                </el-form-item>
                <teacher-dialog
                ref="teacher"
                :list="form.teacher_ids"
                :companyId="form.company_id"
                @addTeacher="addTeacherHandle"/>
                <course-dialog
                ref="course"
                :list="form.course_ids"
                :companyId="form.company_id"
                @addCourse="addCourseHandle"/>
            </el-form>
            <div class="text-center">
                <el-button :loading="posting" type="primary" @click="onSave">保 存</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>

import Tinymce from '../../components/base/Tinymce';
import FileUpload from '../../components/base/FileUpload';
import TeacherDialog from '../../components/dialog/TeacherDialog';
import TeacherList from '../../components/page/TeacherList';
import CourseDialog from '../../components/dialog/CourseDialog';
import CourseList from '../../components/page/CourseList';

export default {
    components: {
        Tinymce,
        TeacherDialog,
        TeacherList,
        CourseDialog,
        CourseList,
        FileUpload,
    },
    data() {
        return {
            posting: false,
            form: {
                name: '',
                content: '',
                type: 1,
                video: '',
                course_ids: [],
                teacher_ids: [],
                teachers: [],
                courses: [],
                company_id: '',
            },
            id: this.$route.params.id,
            courseOptions: [],
            teacherOptions: [],
            originCourses: [],
            originTeachers: [],
            rules: {
                name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' },
                ],
                course_ids: [
                    { required: true, message: '学习主题不能为空', trigger: 'blur' },
                ],
                content: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                ],
            },
        };
    },
    methods: {
        onSave() {
            this.$refs.form.validate(async (valid) => {
                if (!valid) return;
                // 识别视频类型
                // if (this.form.type === 2 && !this.form.video) {
                //     $ele.$message.error('请先上传视频文件或填写视频链接地址');
                //     return;
                // }
                this.posting = true;
                if (this.id) {
                    const res = await API.get(`section/bind/${this.id}`);
                    this.getDiffBindIds(true, res);
                    API.put(`section/${this.id}`, this.form).then(() => {
                        this.$router.go(-1);
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                } else {
                    this.getDiffBindIds(false, []);
                    API.post('section', this.form).then(() => {
                        this.$router.push({name: 'SectionManage'});
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                }
            });
        },
        fetchData() {
            if (this.id) {
                API.get(`section/${this.id}`).then((res) => {
                    for (const i of Object.keys(this.form)) {
                        if (res[i] || res[i] === 0) this.form[i] = res[i];
                    }
                    this.originCourses = res.course_ids;
                    this.originTeachers = res.teacher_ids;
                });
            }
        },
        fetchCourse() {
            API.get('course/list').then((res) => {
                this.courseOptions = res;
            });
        },
        fetchTeacher() {
            API.get('teacher/list').then((res) => {
                this.teacherOptions = res;
            });
        },
        getDiffBindIds(isUpdated, res) {
            if (isUpdated) {
                this.originTeachers = res.teachers ? res.teachers : [];
                this.originCourses = res.courses ? res.courses : [];
            }
            this.form.add_teacher_ids = this.form.teacher_ids.filter(v => this.originTeachers.indexOf(v) === -1);
            this.form.del_teacher_ids = this.originTeachers.filter(v => this.form.teacher_ids.indexOf(v) === -1);
            this.form.add_course_ids = this.form.course_ids.filter(v => this.originCourses.indexOf(v) === -1);
            this.form.del_course_ids = this.originCourses.filter(v => this.form.course_ids.indexOf(v) === -1);
        },
        addTeacherHandle(teacher) {
            if (!this.form.teacher_ids.includes(teacher.id)) {
                this.form.teachers.push(teacher);
                this.form.teacher_ids = [];
                this.form.teachers.map((el) => {
                    this.form.teacher_ids.push(el.id);
                    return el;
                });
            }
            $ele.$message.success('选择讲师成功');
        },
        getTeachers() {
            this.$refs.teacher.open();
        },
        deleteTeacher(index) {
            this.form.teachers.splice(index, 1);
            this.form.teacher_ids = [];
            this.form.teachers.map((el) => {
                this.form.teacher_ids.push(el.id);
                return el;
            });
        },
        addCourseHandle(course) {
            if (!this.form.course_ids.includes(course.id)) {
                this.form.courses.push(course);
                this.form.course_ids = [];
                this.form.courses.map((el) => {
                    this.form.course_ids.push(el.id);
                    return el;
                });
            }
            $ele.$message.success('选择学习主题成功');
        },
        getCourse() {
            this.$refs.course.open();
        },
        deleteCourse(index) {
            this.form.courses.splice(index, 1);
            this.form.course_ids = [];
            this.form.courses.map((el) => {
                this.form.course_ids.push(el.id);
                return el;
            });
        },
    },
    mounted() {
        this.fetchData();
    },
};
</script>

<style lang="scss">
.category-detail-page {
    .input-width {
        width: 300px;
    }
    .picture {
        width: 200px;
        height: 200px;
        line-height: 200px;
    }
    .uploader-icon {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
    }
    .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
}
</style>
